/**
 * 新闻列表页面
 *
 * 这个页面展示了：
 * 1. 新闻列表展示
 * 2. 分类筛选
 * 3. 搜索功能
 * 4. 分页处理
 */
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useNews } from '@/hooks/useNews';
import Navbar from '@/components/Navbar';

export default function News() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 12;

  // 获取新闻数据
  const {
    data: newsData,
    isLoading,
    error
  } = useNews({
    search: searchTerm,
    category: selectedCategory,
    page: currentPage,
    size: pageSize,
    published_only: true
  });

  // 新闻分类
  const categories = [
    '公司新闻',
    '行业动态',
    '政策法规',
    '技术分享',
    '案例分析'
  ];

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1);
  };

  // 处理分类筛选
  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category === selectedCategory ? '' : category);
    setCurrentPage(1);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      {/* 页面头部 */}
      <div className="bg-white border-b">
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
              新闻动态
            </h1>
            <p className="text-lg text-gray-600 max-w-2xl mx-auto">
              了解最新的环境工程行业动态、政策法规和技术发展
            </p>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* 侧边栏 */}
          <div className="lg:w-1/4">
            <div className="bg-white rounded-lg shadow-md p-6 mb-6">
              {/* 搜索 */}
              <h3 className="text-lg font-semibold text-gray-900 mb-4">搜索新闻</h3>
              <form onSubmit={handleSearch}>
                <div className="flex">
                  <input
                    type="text"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    placeholder="输入关键词..."
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  <button
                    type="submit"
                    className="px-4 py-2 bg-blue-600 text-white rounded-r-lg hover:bg-blue-700 transition-colors"
                    aria-label="搜索新闻"
                  >
                    <i className="fa-solid fa-search"></i>
                  </button>
                </div>
              </form>
            </div>

            {/* 分类筛选 */}
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">新闻分类</h3>
              <div className="space-y-2">
                <button
                  type="button"
                  onClick={() => handleCategoryChange('')}
                  className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
                    selectedCategory === ''
                      ? 'bg-blue-100 text-blue-800'
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  全部分类
                </button>
                {categories.map((category) => (
                  <button
                    key={category}
                    type="button"
                    onClick={() => handleCategoryChange(category)}
                    className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
                      selectedCategory === category
                        ? 'bg-blue-100 text-blue-800'
                        : 'text-gray-700 hover:bg-gray-100'
                    }`}
                  >
                    {category}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* 主要内容 */}
          <div className="lg:w-3/4">
            {/* 加载状态 */}
            {isLoading && (
              <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
                {[...Array(6)].map((_, index) => (
                  <div key={index} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
                    <div className="h-48 bg-gray-200"></div>
                    <div className="p-6">
                      <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
                      <div className="h-6 bg-gray-200 rounded w-3/4 mb-3"></div>
                      <div className="h-4 bg-gray-200 rounded w-full mb-2"></div>
                      <div className="h-4 bg-gray-200 rounded w-2/3"></div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* 错误状态 */}
            {error && (
              <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
                <i className="fa-solid fa-exclamation-triangle text-red-500 text-2xl mb-4"></i>
                <p className="text-red-700">加载新闻失败，请稍后重试</p>
              </div>
            )}

            {/* 新闻列表 */}
            {!isLoading && !error && newsData && (
              <>
                {newsData.items.length > 0 ? (
                  <>
                    <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6 mb-8">
                      {newsData.items.map((news) => (
                        <Link
                          key={news.id}
                          to={`/news/${news.id}`}
                          className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow group"
                        >
                          {/* 新闻图片 */}
                          <div className="relative h-48 overflow-hidden">
                            {news.cover_image ? (
                              <img
                                src={news.cover_image}
                                alt={news.title}
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                onError={(e) => {
                                  const target = e.target as HTMLImageElement;
                                  target.src = '';
                                }}
                              />
                            ) : (
                              <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                                <i className="fa-solid fa-newspaper text-gray-400 text-3xl"></i>
                              </div>
                            )}

                            {/* 置顶标识 */}
                            {news.is_featured && (
                              <div className="absolute top-3 left-3">
                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-500 text-white">
                                  <i className="fa-solid fa-star mr-1"></i>
                                  置顶
                                </span>
                              </div>
                            )}
                          </div>

                          {/* 新闻内容 */}
                          <div className="p-6">
                            <div className="flex items-center justify-between mb-3">
                              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                {news.category}
                              </span>
                              <span className="text-sm text-gray-500">
                                {formatDate(news.published_at)}
                              </span>
                            </div>

                            <h3 className="text-lg font-semibold text-gray-900 mb-3 line-clamp-2 group-hover:text-blue-600 transition-colors">
                              {news.title}
                            </h3>

                            {news.excerpt && (
                              <p className="text-gray-600 text-sm line-clamp-3 mb-4">
                                {news.excerpt}
                              </p>
                            )}

                            <div className="flex items-center justify-between text-sm text-gray-500">
                              <span>
                                <i className="fa-solid fa-user mr-1"></i>
                                {news.author}
                              </span>
                              <span>
                                <i className="fa-solid fa-eye mr-1"></i>
                                {news.view_count} 浏览
                              </span>
                            </div>
                          </div>
                        </Link>
                      ))}
                    </div>

                    {/* 分页 */}
                    {newsData.total > pageSize && (
                      <div className="flex justify-center">
                        <div className="flex items-center space-x-2">
                          <button
                            type="button"
                            onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                            disabled={currentPage === 1}
                            className="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                            aria-label="上一页"
                          >
                            <i className="fa-solid fa-chevron-left"></i>
                          </button>

                          <span className="px-4 py-2 text-sm text-gray-700">
                            第 {currentPage} 页，共 {Math.ceil(newsData.total / pageSize)} 页
                          </span>

                          <button
                            type="button"
                            onClick={() => setCurrentPage(Math.min(Math.ceil(newsData.total / pageSize), currentPage + 1))}
                            disabled={currentPage >= Math.ceil(newsData.total / pageSize)}
                            className="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                            aria-label="下一页"
                          >
                            <i className="fa-solid fa-chevron-right"></i>
                          </button>
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <div className="text-center py-12">
                    <i className="fa-solid fa-newspaper text-gray-400 text-6xl mb-4"></i>
                    <h3 className="text-xl font-semibold text-gray-900 mb-2">暂无新闻</h3>
                    <p className="text-gray-600">
                      {searchTerm || selectedCategory ? '没有找到符合条件的新闻' : '还没有发布任何新闻'}
                    </p>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}